function MyPromise(executor) {
    const PENDING = "pending";
    const FULFILLED = "fulfilled";
    const REJECTED = "rejected";

    let state = PENDING;
    let value = undefined;
    let reason = undefined;
    let onFulfilledCallbacks = [];
    let onRejectedCallbacks = [];

    const resolve = (newValue) => {
        if (state !== PENDING) return;
        state = FULFILLED;
        value = newValue;
        onFulfilledCallbacks.forEach((cb) => cb(value));
    };

    const reject = (error) => {
        if (state !== PENDING) return;
        state = REJECTED;
        reason = error;
        onRejectedCallbacks.forEach((cb) => cb(reason));
    };

    try {
        executor(resolve, reject);
    } catch (error) {
        reject(error);
    }

    this.then = (onFulfilled, onRejected) => {
        onFulfilledCallbacks.push(() => {
            try {
                onFulfilled(value);
            } catch (error) {
                reject(error);
            }
        });
        onRejectedCallbacks.push(() => {
            try {
                onRejected(reason);
            } catch (error) {
                reject(error);
            }
        });
    };
}

// 使用示例
function asyncTask() {
    return new MyPromise((resolve, reject) => {
        setTimeout(() => {
            resolve("Task completed");
        }, 1000);
    });
}

// asyncTask().then((result) => console.log(result));
asyncTask().then(function (result) {
    console.log(result);
});
// .catch((error) => console.error(error));
